import 'package:dio/dio.dart' as request;
import 'package:flutter_demo/entities/base_response.dart';
import 'package:get/get.dart';

import '../entities/user.dart';

class UserController extends GetxController {
  static const kPostUrl = "https://fourpetal.com/wp-admin/admin-ajax.php";
  final _user = User().obs;
  final _dio = request.Dio()..options = request.BaseOptions(contentType: request.Headers.formUrlEncodedContentType);

  isLogin() {
    return _user.value.id != null;
  }

  User getUser() {
    return _user.value;
  }

  Future<BaseResponse> login(String username, String pwd) async {
    final data = {
      "action": "user_login",
    };
    data["username"] = username;
    data["password"] = pwd;
    return await _postData(data);
  }

  logout() {}

  register(Map<String, String?> formData) async {
    final data = {
      "action": "user_register",
    };
    data["user_name"] = formData["username"]!;
    data["user_email"] = formData["email"]!;
    data["user_pass"] = formData["pwd"]!;
    data["user_pass2"] = formData["re_pwd"]!;
    data["captcha"] = formData["code"]!;
    return await _postData(data);
  }

  sendCode(String email) async {
    final data = {
      "action": "captcha_email",
    };
    data["user_email"] = email;
    return await _postData(data);
  }

  _postData(Map<String, String> data) async {
    try {
      var response = await _dio.post(kPostUrl, data: data);
      return BaseResponse.fromMap(response.data);
    } catch (e) {
      return BaseResponse(status: "0", msg: e.toString());
    }
  }
}
